package com.hspedu.hspmybatis.sqlsession;



import com.hspedu.entity.Monster;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class HspExecutor implements Executor{
    private HspConfiguration hspConfiguration=new HspConfiguration();
    @Override
    public <T> T query(String sql, Object parameter) {
        Connection connection = getConnection();
        ResultSet resultSet=null;
        PreparedStatement preparedStatement=null;
        try {
            preparedStatement=connection.prepareStatement(sql);
            //设置参数
            preparedStatement.setString(1,parameter.toString());
            //实现查询返回结果
            resultSet=preparedStatement.executeQuery();
            Monster monster = new Monster();
            while (resultSet.next()){
                monster.setId(resultSet.getInt("id"));
                monster.setName(resultSet.getString("name"));
                monster.setEmail(resultSet.getString("email"));
                monster.setAge(resultSet.getInt("age"));
                monster.setGender(resultSet.getInt("gender"));
                monster.setSalary(resultSet.getDouble("salary"));
                monster.setBirthday(resultSet.getDate("birthday"));
            }
            return (T) monster;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (resultSet!=null){
                    resultSet.close();
                }
                if (preparedStatement!=null){
                    preparedStatement.close();
                }
                if (connection!=null){
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Connection getConnection(){
        Connection build = hspConfiguration.build("hsp_mybatis.xml");
        return build;
    }
}
